import 'dart:convert';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/bean/attend_record_calendar_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import 'attendance_record_today_viewmodel.dart';

class AttendRecordCalendarViewModel extends BaseViewModel {
  final String fuid;
  AttendRecordCalendarViewModel(BaseState<StatefulWidget> state,this.fuid) : super(state){
    dateInfoValueNotifier = ValueNotifier(null);
  }

  ///根据月份时间戳 存储对应Json串
  Map<String, String> monthMap = Map();

  ///具体信息
  ValueNotifier<AttendRecordCalendarDataBean> dateInfoValueNotifier;

  ///最新月份响应
  String latestMonthTimestramp;


  ///按月获取记录请求
  void faceRecordUpdate(BuildContext context,int fpid,String type,String backup,String fuid,String cpid,int punchdate) {
    if(fpid==null){
      VgToastUtils.toast(context, "打卡信息错误");
      return;
    }
    if(punchdate!=0 && punchdate!=null){
      //秒转字符串
      String  timeStr = DateUtil.formatDateMs(punchdate * 1000, format: "yyyy-MM-dd");
      //字符串转秒
      punchdate =  (DateTime.parse(timeStr).millisecondsSinceEpoch/1000)?.toInt();
    }

    VgHttpUtils.get(ServerApi.BASE_URL + "app/appFaceRecordUpdate",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "type": type ?? "00",
          "fuid": fuid?? "",
          "backup":backup ?? "",
          "fpid":fpid ?? "",
          "cpid":cpid??"",
          "punchdate":punchdate??0
        },
        callback: BaseCallback(
            onSuccess: (val){
              VgEventBus.global.send(ModifyAttendanceRefreshEvent());
              RouterUtils.pop(context);
            },
            onError: (msg){

            }
        ));
  }

  ///按月获取记录请求
  void getRecordByMonthHttp(String monthTimestramp, bool isReadCache, bool isPageChangeNotifier,BaseCallback callback) {
    if (monthTimestramp == null) {
      _pageNotifier(monthTimestramp,null,isPageChangeNotifier);
      return;
    }
    if(isPageChangeNotifier) {
      latestMonthTimestramp = monthTimestramp;
    }
    if(isReadCache ?? false) {
      if (monthMap.containsKey(monthTimestramp)) {
        String jsonValue = monthMap[monthTimestramp];
        if (jsonValue != null && jsonValue.isNotEmpty) {
          AttendRecordCalendarResponseBean bean = AttendRecordCalendarResponseBean
              .fromMap(json.decode(jsonValue));
          _pageNotifier(monthTimestramp,bean?.data,isPageChangeNotifier);
          callback?.onSuccess(json.decode(jsonValue));
          return;
        }
      }
    }

    VgHttpUtils.get(ServerApi.BASE_URL + "app/appMonthPunchForFaceUser",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "dayTime": monthTimestramp ?? "",
          "fuid": fuid?? "",
        },
        callback: BaseCallback(
          onSuccess: (val){
            loading(false);
            AttendRecordCalendarResponseBean bean = AttendRecordCalendarResponseBean.fromMap(val);
            monthMap[monthTimestramp] = json.encode(bean);
            _pageNotifier(monthTimestramp,bean?.data,isPageChangeNotifier);
            callback?.onSuccess(val);
          },
          onError: (msg){
            callback?.onError(msg);
            _pageNotifier(monthTimestramp,null,isPageChangeNotifier);
          }
        ));
  }

  ///通知页面数据刷新
  void _pageNotifier(String monthTimestramp,AttendRecordCalendarDataBean dataBean,bool isPageChangeNotifier){
    if(!(isPageChangeNotifier ?? false)){
      return;
    }
    if(latestMonthTimestramp != monthTimestramp){
      print("更新不及时，拦截下来");
      return;
    }
    Future.delayed(Duration(milliseconds: 0), () {
      print("数据更新:${DateTime.fromMillisecondsSinceEpoch(int.parse(monthTimestramp) *1000)}");
      dateInfoValueNotifier.value = dataBean;
    });
  }


  @override
  void onDisposed() {
    monthMap?.clear();
    monthMap = null;
    dateInfoValueNotifier?.dispose();
    super.onDisposed();
  }
}

class CardMultiRefreshEvent{
  final PunchRecordBean item;

  CardMultiRefreshEvent(this.item);
}